package com.komorebi.controller;


import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.komorebi.common.Result;
import com.komorebi.entity.SysMenu;
import com.komorebi.entity.SysRoleMenu;
import com.komorebi.entity.SysUser;
import com.komorebi.service.SysMenuService;
import com.komorebi.vo.SysMenuVo;
import org.apache.tomcat.jni.Local;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author komorebi
 * @since 2021-11-19
 */
@RestController
@RequestMapping("/sys/menu")
public class SysMenuController extends BaseController {

    //获取当前用户菜单和权限信息
    @GetMapping("/nav")
    public Result nav(Principal principal){
        //Principal会保留用户信息
        //获取当前用户
        SysUser sysUser = sysUserService.getByUserName(principal.getName());
        //获取当前用户权限字符串，逗号分隔
        String authorityInfo = sysUserService.getUserAuthority(sysUser.getId());

        //工具包将字符串转为数组
        String [] authorityInfoArray = StringUtils.tokenizeToStringArray(authorityInfo,",");
        //获取导航栏
        List<SysMenuVo> navs = sysMenuService.getCurrentUserNav();
        return Result.success(MapUtil.builder()
                .put("authorities",authorityInfoArray)
                .put("nav",navs)
                .map());
    }
    @GetMapping("/info/{id}")
    @PreAuthorize("hasAuthority('sys:menu:list')")
    public Result getMenuInfo(@PathVariable(name = "id") Long id){
        return Result.success(sysMenuService.getById(id));
    }
    //获取系统所有菜单项
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:menu:list')")
    public Result getMenuList(){
        return Result.success(sysMenuService.tree());
    }
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('sys:menu:save')")
    public Result saveMenuInfo(@Validated @RequestBody SysMenu sysMenu){
        //@Validated检验实体异常，具体内容看对应实体类
        //@RequestBody表示参数在请求体中
        sysMenu.setCreated(LocalDateTime.now());
        sysMenuService.save(sysMenu);
        return Result.success(sysMenu);
    }
    @PostMapping("/update")
    @PreAuthorize("hasAuthority('sys:menu:update')")
    public Result updateMenuInfo(@Validated @RequestBody SysMenu sysMenu){
        sysMenu.setUpdated(LocalDateTime.now());
        sysMenuService.updateById(sysMenu);
        //修改菜单信息后需要清除所有与该菜单相关的权限缓存
        sysUserService.clearUserAuthorityInfoByMenuId(sysMenu.getId());
        return Result.success(sysMenu);
    }
    @GetMapping("delete/{id}")
    @PreAuthorize("hasAuthority('sys:menu:delete')")
    public Result deleteMenuInfo(@PathVariable(name = "id") Long id){
        //删除菜单项前提，先删除子菜单项，否则提示失败
        int count = sysMenuService.count(new QueryWrapper<SysMenu>().eq("parent_id", id));
        if(count > 0){
            return Result.fail("请先删除子菜单");
        }
        sysUserService.clearUserAuthorityInfoByMenuId(id);
        //删除菜单项
        sysMenuService.removeById(id);
        //中间表role_menu相关信息也要删除
        sysRoleMenuService.remove(new QueryWrapper<SysRoleMenu>().eq("menu_id",id));
        return Result.success("删除成功");
    }
}
